<template>
  <div class="mod-config">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <b>数据集</b>
            <div style="float: right;">
              <el-button type="primary" icon="el-icon-plus" @click="searchReset" circle title="新增"></el-button>
              <el-button type="primary" icon="el-icon-info" circle title="详情"></el-button>
              <el-button type="primary" icon="el-icon-edit" circle title="编辑"></el-button>
              <el-button type="primary" icon="el-icon-delete" @click="deleteHandle" circle title="删除"></el-button>
            </div>
          </div>
          <el-input class="search" placeholder="输入关键字进行过滤" v-model="filterText">
          </el-input>

          <el-tree class="filter-tree" :data="CategOptions" :props="defaultProps" default-expand-all
            :filter-node-method="filterNode" ref="tree" @node-click="getData">
          </el-tree>
        </el-card>
      </el-col>
      <!-- 新增 -->
      <el-col :span="18">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <b>新增数据源</b>
          </div>
          <div class="text item" style="padding-right: 20px;">
            <el-form label-width="100px">
              <el-form-item label="名称">
                <el-input v-model="dataForm.type"></el-input>
              </el-form-item>
              <el-form-item label="数据源">
                <el-select v-model="dataForm.name">
                  <el-option v-for="item in sour" :key="item" :value="item"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="查询语句">
                <code-mirror :value="dataForm.sentence" ref="codeMirrorDialog" @getCodeMirror="getCodeData"></code-mirror>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" class="button" @click="selectList()">读取数据</el-button>
              </el-form-item>
              <el-form-item label="实时间隔(秒)">
                <el-input v-model="dataForm.userName"></el-input>
              </el-form-item>
            </el-form>
            <el-row :gutter="20">
              <el-col :span="12">
                <div style="width: 100%;min-height: 140px;border: dashed 2px #e7e7e7;">
                  <draggable v-model="fieldName" :group="{name: 'field',pull: 'clone',put: false}" :options="{sort: false}"
                    @end="endDrag">
                    <el-button type="info" style="margin: 3px;" v-for="(item,index) in fieldName" :key="index">{{item}}</el-button>
                  </draggable>
                </div>
              </el-col>
              <el-col :span="12">
                <div style="width: 100%;min-height: 140px;border: dashed 2px #e7e7e7;">

                  <ul class="field-ul">
                    <h3>维度列</h3>
                    <draggable id="dimensionList" v-model="dimensionList" :options="{group:'field'}" style="min-height: 60px;">
                      <li v-for="(element,index) in dimensionList" :key="'dimension'+index">
                        <span style="margin-right: 10px;">
                          <img src="../../../const/cboard/bullet_blue.png" style="vertical-align: middle;">
                        </span>
                        <span v-if="element.alias">{{element.alias}}({{element.column}})</span>
                        <span v-else>{{element.column}}</span>
                        <span>
                          <span style="margin-left: 5px;" @click="editHandle(element,index)"><i class="el-icon-edit"></i></span>
                          <span style="margin-left: 5px;" @click="dimensionDelHandle(index)"><i class="el-icon-delete"></i></span>
                        </span>
                      </li>
                    </draggable>
                  </ul>


                  <ul class="field-ul">
                    <h3>指标列</h3>
                    <draggable id="targetList" v-model="targetList" :options="{group:'field'}" style="min-height: 60px;">
                      <li v-for="(element,index) in targetList" :key="'target'+index">
                        <span style="margin-right: 10px;">
                          <img src="../../../const/cboard/bullet_red.png" style="vertical-align: middle;">
                        </span>
                        <span v-if="!element.alias">{{element.column}}</span>
                        <span v-if="element.alias">{{element.alias}}({{element.column}})</span>
                        <span>
                          <span style="margin-left: 5px;" @click="editText(index)"><i class="el-icon-edit"></i></span>
                          <div v-if="inputShow == index + 1" style="display: inline-block;width: 90px; margin-left: 5px;">
                            <el-input v-model="element.alias" @change="targetAliasChange(index,arguments)"></el-input>
                          </div>
                          <span style="margin-left: 5px;" @click="targetDelHandle(index)"><i class="el-icon-delete"></i></span>
                        </span>
                      </li>
                    </draggable>
                  </ul>

                  <ul class="field-ul">
                    <h3>
                      <span>可选表达式</span>
                      <el-button type="primary" size="mini" icon="el-icon-plus" circle title="新增" style="margin-left: 6px;padding: 3px;"
                        @click="expAddOrUpdate('add',{})"></el-button>
                    </h3>
                    <li v-for="(expressionItem,expressionIndex) in expressionList" :key="'expression'+expressionIndex">
                      <span style="margin-right: 10px;">
                        <img src="../../../const/cboard/bullet_red.png" style="vertical-align: middle;">
                      </span>
                      <span>{{expressionItem.alias}}</span>
                      <span>
                        <span style="margin-left: 5px;" @click="expAddOrUpdate('update',expressionItem)"><i class="el-icon-edit"></i></span>
                        <span style="margin-left: 5px;" @click="expDelHandle(expressionIndex)"><i class="el-icon-delete"></i></span>
                      </span>
                    </li>
                  </ul>

                  <ul class="field-ul">
                    <h3>
                      <span>可选过滤</span>
                      <el-button type="primary" size="mini" icon="el-icon-plus" circle title="新增" style="margin-left: 6px;padding: 3px;"
                        @click="filterAddOrUpdate('add',{})"></el-button>
                    </h3>
                    <li v-for="(filterItem,filterIndex) in filterList" :key="'filter'+filterIndex">
                      <span style="margin-right: 10px;">
                        <img src="../../../const/cboard/bullet_red.png" style="vertical-align: middle;">
                      </span>
                      <span>{{filterItem.group}}</span>
                      <span>
                        <span style="margin-left: 5px;" @click="filterAddOrUpdate('update',filterItem)"><i class="el-icon-edit"></i></span>
                        <span style="margin-left: 5px;" @click="filterDelHandle(filterIndex)"><i class="el-icon-delete"></i></span>
                      </span>
                    </li>
                  </ul>
                </div>
              </el-col>
            </el-row>
            <div style="height: 33px;margin-top: 10px;">
              <div style="float: right;">
                <el-button type="primary" class="button">测试</el-button>
                <el-button type="success" class="button" @click="saveData()">保存</el-button>
                <el-button type="danger" class="button">取消</el-button>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <!-- 弹窗，编辑 -->
    <edit-dialog v-if="editVisible" ref="editDialog" :title="title" @refreshData="getAliasData"></edit-dialog>

    <!-- 弹窗, 表达式 -->
    <check-test v-if="testVisible" ref="testDialog" @refreshParams="getExpressionData"></check-test>

    <!-- 弹窗，可选过滤 -->
    <filter-select v-if="filterVisible" ref="filterDialog" @refreshParams="getFilterData"></filter-select>
  </div>
</template>

<script>
  import CodeMirror from '../components/CodeMirror' // 编辑器

  import draggable from 'vuedraggable' // 拖拽

  import EditDialog from './edit'

  import {
    CategoryList,
    DatasetList,
    getColumns,
    sourList,
    saveNewDataset,
    getDatasource,
    getDataSetName,
    deleteDataset
  } from '@/api/cboard/cboard'

  import CheckTest from './test'

  import FilterSelect from './filter'


  export default {
    data() {
      return {
        editVisible: false,
        testVisible: false,
        filterVisible: false,
        inputShow: '',
        title: '',
        dataForm: {
          datasetId: '',
          type: '',
          name: '',
          sentence: ''
        },
        JsonData: {
          id: '',
          categoryName: '',
          name: '',
          data: {
            datasource: '',
            selects: [],
            expressions: [],
            filters: [],
            query: {
              sql: []
            },
            schema: {
              dimension: [],
              measure: []
            }
          },
        },
          JsonColumns: {
              datasourceId: '',
              query: '',
              datasetId: '',
              reload: false,
          },
        dataSet: {},
        sour: [],
        selectorList: [{
            value: 1,
            label: 'Elasticsearch'
          },
          {
            value: 2,
            label: 'Solr'
          },
          {
            value: 3,
            label: 'saiku'
          },
          {
            value: 4,
            label: 'TextFile'
          },
          {
            value: 5,
            label: 'jdbc'
          },
          {
            value: 6,
            label: 'kylin'
          },
        ],
        filterText: '',
        CategOptions: [],
        defaultProps: {
          children: 'children',
          label: 'name'
        },

        // 字段名
        fieldName: [],
        dimensionList: [],
        targetList: [],
        expressionList: [],
        filterList: []
      }
    },
    components: {
      CodeMirror,
      draggable,
      EditDialog,
      CheckTest,
      FilterSelect
    },
    created() {
      this.getDatasetCategoryList();

      this.getSourList();
    },
    methods: {
      getData(data) {
        this.dataSet = data;
        this.$set(this.dataForm, 'sentence', data.data.query.sql)
        this.$nextTick(() => {
          this.$refs.codeMirrorDialog.huixian()
        })
        getDataSetName(data.data.datasource).then(response => {
          this.dataForm.name = response.data;
        })
        this.dataForm.type = data.name;
        this.fieldName = data.data.selects;
        this.dataForm.datasetId = data.id;
        this.dimensionList = data.data.schema.dimension;
        this.targetList = data.data.schema.measure;
        this.expressionList = data.data.expressions
        this.filterList = data.data.filters
        this.dataForm = { ...this.dataForm
        }
      },
      saveData() {
        let datasource;
        getDatasource(this.dataForm.name).then(response => {
          if (response.data.id) {
            datasource = response.data.id;
          }
          this.JsonData.data.schema.dimension = this.dimensionList;
          this.JsonData.data.schema.measure = this.targetList;
          this.JsonData.categoryName = this.dataSet.categoryName;
          this.JsonData.id = this.dataSet.id;
          this.JsonData.data.selects = this.fieldName;

          this.JsonData.data.expressions = this.expressionList
          this.JsonData.data.filters = this.filterList

          this.JsonData.data.datasource = datasource;
          this.JsonData.data.query.sql = this.dataForm.sentence;
          this.JsonData.name = this.dataForm.type;
          let data = this.JsonData;

          console.log(data)
          saveNewDataset(data).then(() => {
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
          })
        })
      },
      /*获取数据源*/
      getSourList() {
        sourList().then(response => {
          this.soursOptions = response.data
          let list = []
          this.soursOptions.forEach(item => {
            list.push(item.name)
          })
          this.sour = list
        })

      },
      /*获取数据集分类*/
      getDatasetCategoryList() {
        CategoryList().then(response => {
          let resultData = response.data
          let list = []
          resultData.forEach((item, index) => {
            let obj = {}
            obj.parentId = 0
            obj.id = index
            obj.name = item
            obj.children = []
            list.push(obj)
          })
          this.CategOptions = list
          this.getDatasetList()
        })
      },
      /*获取数据集*/
      getDatasetList() {
        DatasetList().then(response => {
          let resultData = response.data
          resultData.forEach((item, index) => {
            for (let i = 0; i < this.CategOptions.length; i++) {
              if (item.categoryName == this.CategOptions[i].name) {
                item.parentId = this.CategOptions[i].id
                item.children = []
                this.CategOptions[i].children.push(item)
              }
            }
          })
        })
      },
      selectList() {
        let reload = false;
        if (this.dataSet.id) {
          this.dataForm.datasetId = this.dataSet.id;
        } else {
          this.dataForm.datasetId = 999;
        }
        let datasourceId = this.dataForm.name;
        let query = this.dataForm.sentence
        getDatasource(this.dataForm.name).then(response => {
          if (response.data.id)
            datasourceId = response.data.id;
            this.JsonColumns.datasetId = this.dataForm.datasetId
            this.JsonColumns.datasourceId = datasourceId
            this.JsonColumns.query = query;
            this.JsonColumns.reload = reload;
          getColumns(this.JsonColumns).then(response => {
            this.fieldName = response.data.columns
          })
        })

      },
      //清空
      searchReset() {
        for (let key in this.dataForm) {
          this.dataForm[key] = ''
        }
        this.$set(this.dataForm, 'sentence', '');
        this.$nextTick(() => {
          this.$refs.codeMirrorDialog.huixian()
        })
        this.dataSet.id = '';
        this.fieldName = [];
        this.dimensionList = [];
        this.targetList = [];
        this.expressionList = [];
        this.filterList =[];
      },

      // 删除数据源
      deleteHandle() {
        let id = this.dataSet.id;
        this.$confirm('是否确认删除名称为' + this.dataSet.name, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          return deleteDataset(id)
        }).then(data => {
          this.$message.success('删除成功')
          //this.getDatasetList()
        })
      },
      // 树结构查询事件
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      // 获取查询语句
      getCodeData(data) {
        this.$set(this.dataForm, 'sentence', data)
      },
      editHandle(element,index) {
        this.editVisible = true
        this.title = element.column
        this.$nextTick(() => {
          this.$refs.editDialog.init(index)
        })
      },
      getAliasData(data){
        this.dimensionList[data.index]['alias'] = data.alias
        this.dimensionList = [...this.dimensionList]
      },
      editText(idx) {
        this.inputShow = idx + 1
      },
      endDrag(evt) {
        let name = evt.item.textContent
        if (evt.to.id === 'dimensionList') {
          let code = this.dimensionList.slice(-1) || 0
          this.dimensionList[evt.newIndex] = {
            type: 'column',
            column: name,
            id: ''
          }
          this.dimensionList = [...this.dimensionList]
        } else if (evt.to.id === 'targetList') {
          let code = this.targetList.slice(-1) || 0
          this.targetList[evt.newIndex] = {
            type: 'column',
            column: name,
            id: ''
          }
          this.targetList = [...this.targetList]
        }
      },
      // 打开表达式弹窗
      expAddOrUpdate(type, data) {
        this.testVisible = true
        this.$nextTick(() => {
          this.$refs.testDialog.init(type, data, this.fieldName)
        })
      },
      // 获取表达式数据
      getExpressionData(row) {
        if (row.type == 'add') {
          this.expressionList.push(row.data)
        } else if (row.type == 'update') {
          this.expressionList.forEach((item, index) => {
            if (item.timestamp == row.data.timestamp) {
              this.expressionList[index] = row.data
            }
          })
        }
        this.expressionList = [...this.expressionList]
      },
      // 删除表达式
      expDelHandle(index) {
        this.expressionList.splice(index, 1)
      },
      // 打开过滤弹窗
      filterAddOrUpdate(type, data) {
        let list = this.targetList.concat(this.dimensionList)
        let datasetId = this.dataForm.datasetId
        this.filterVisible = true
        this.$nextTick(() => {
          this.$refs.filterDialog.init(type, datasetId, data, list)
        })
      },
      // 获取可选过滤数据
      getFilterData(row) {
        if (row.type == 'add') {
          this.filterList.push(row.data)
        } else if (row.type == 'update') {
          this.filterList.forEach((item, index) => {
            if (item.timestamp == row.data.timestamp) {
              this.filterList[index] = row.data
            }
          })
        }
        this.filterList = [...this.filterList]
      },
      // 删除可选过滤
      filterDelHandle(index) {
        this.filterList.splice(index, 1)
      },
      // 删除
      dimensionDelHandle(index) {
        this.dimensionList.splice(index, 1)
      },
      targetDelHandle(index) {
        this.targetList.splice(index, 1)
      },
      // 指标项别名
      targetAliasChange(index) {
        this.targetList[index].alias = arguments[1][0]
        this.inputShow = 0
      }
    },
    watch: {
      filterText(val) {
        this.$refs.tree.filter(val);
      }
    },
  }
</script>

<style lang="scss" scoped>
  .mod-config {
    padding: 10px 15px;
  }

  /deep/ .el-card {
    background-color: #fff;
  }

  /deep/ .el-card__body {
    padding: 0;
    padding-bottom: 20px;
  }

  .box-card .item {
    padding-left: 20px;
    padding-bottom: 10px;
    padding-top: 10px;
    border-bottom: solid 1px #e7e7e7;
  }

  .search {
    padding: 20px 20px 0 20px;
  }

  .filter-tree {
    margin-top: 20px;
  }

  /deep/ .el-tree {
    background-color: #fff;
  }

  .field-ul {
    padding-left: 24px;

    li {
      padding-left: 10px;
    }
  }
</style>
